﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace EnterpriseFramework.DataAccess.Provider
{
    public class DataCollection<T> : IDataCollection<T>
    {
        IDbCommand cmd;
        AbstractColumn[] columns;
        Type type;
        public DataCollection(IDbCommand cmd, AbstractColumn[] columns)
            : this(cmd)
        {
            this.columns = columns;
        }
        public DataCollection(IDbCommand cmd)
        {
            type = typeof(T);
            this.cmd = cmd;
        }
        public Entities<T> DataAsList()
        {
            Entities<T> result = new Entities<T>();
            result.ISNewList = false;
            IDataReader reader = null;
            try
            {
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    var target = type.GetConstructors()[0].Invoke(null);
                    //object target = Activator.CreateInstance(type, true);

                    foreach (AbstractColumn column in columns)
                    {
                        if (column.Writeable && column.Included)
                        {
                            var val = reader[column.Name];
                            if (DBNull.Value.Equals(val))
                                column.Write(target, null);
                            else
                                column.Write(target, val);
                        }
                    }
                    result.Add((T)target);
                }
                return result;
            }
            catch (Exception ex)
            {
                //<e> 4
            }
            finally
            {
                if (reader != null && !reader.IsClosed)
                    reader.Close();
                if (cmd != null)
                    cmd.Dispose();
            }
            return new Entities<T>();
        }

        public DataTable DataAsDataTable()
        {
            IDataReader reader = null;
            try
            {
                DataTable dt = new DataTable();
                dt.Load(cmd.ExecuteReader());
                return dt;
            }
            catch (Exception ex)
            {
                //<e> 4
            }
            finally
            {
                if (reader != null && !reader.IsClosed)
                    reader.Close();
                if (cmd != null)
                    cmd.Dispose();
            }
            return default(DataTable);
        }

        public IDbCommand DBCommand
        {
            get { return cmd; }
            set { cmd = value; }
        }

        public AbstractColumn[] Columns
        {
            get { return columns; }
            set { columns = value; }
        }
    }
}
